package utils;

import java.util.ArrayList;
import java.util.List;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;

import rasterprimate.Constants;
import rasterprimate.Primate;
import rasterprimate.PrimateTopo;
import rasterprimate.Resource;
import repast.simphony.query.space.grid.GridCell;
import repast.simphony.random.RandomHelper;
import repast.simphony.space.gis.Geography;
import repast.simphony.space.grid.GridPoint;
import repast.simphony.util.ContextUtils;

public final strictfp class SimUtils {

	public static <T> T randomElementOf(final List<T> list) {
		return list.get(RandomHelper.nextIntFromTo(0, list.size() - 1));
	}

	public static <T> List<GridCell<T>> getFreeGridCells(
			final List<GridCell<T>> neighborhood) {
		final ArrayList<GridCell<T>> ret = new ArrayList<GridCell<T>>();

		for (final GridCell<T> act : neighborhood) {
			if (0 == act.size()) {
				ret.add(act);
			}
		}

		return ret;
	}
	
	public static Resource findMyCurrentResource(Primate p, Geography geog){
		double dist = 0, minDist = 9999;
		Resource closestR = null;
		
			//find all resources near by
				Envelope foodSite = new Envelope();
				foodSite.init(p.getCoord());
				foodSite.expandBy((2.0*Constants.cellSize));///(degToMeters));
				Iterable<Resource> primateFood = geog.getObjectsWithin(foodSite,Resource.class);
				foodSite.setToNull();

				//which one is the closest one to me
				while (primateFood.iterator().hasNext()==true){
					Resource rMaybe=primateFood.iterator().next();
					dist = p.getCoord().distance(rMaybe.getCoord());
					if (dist<minDist){
						closestR=rMaybe;
						minDist = dist;
					}
				}
				//if i've found no resources
				if (closestR==null){
					System.out.println("for some strange reason i'm not in a resource!!");
				}
		
		return closestR;
	}
	
	public static Resource findMyCurrentResource(PrimateTopo p, Geography geog){
		double dist = 0, minDist = 9999;
		Resource closestR = null;
		
			//find all resources near by
				Envelope foodSite = new Envelope();
				foodSite.init(p.getCoord());
				foodSite.expandBy((2.0*Constants.cellSize));
				Iterable<Resource> primateFood = geog.getObjectsWithin(foodSite,Resource.class);
				foodSite.setToNull();

				//which one is the closest one to me
				while (primateFood.iterator().hasNext()==true){
					//System.out.println("found some resource nearby!");
					Resource rMaybe=primateFood.iterator().next();
					dist = p.getCoord().distance(rMaybe.getCoord());
					if (dist<minDist){
						closestR=rMaybe;
						minDist = dist;
					}
				}
				//if i've found no resources
				if (closestR==null){
					System.out.println("for some strange reason i'm not in a resource!!");
				}
		
		return closestR;
	}
}
